package com.colbby.datahouse.db.spring;

import java.sql.Connection;
import java.sql.SQLException;

import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.support.AbstractPlatformTransactionManager;
import org.springframework.transaction.support.DefaultTransactionStatus;

import com.colbby.datahouse.message.ConnectionUtils;

public class TransactionManager extends AbstractPlatformTransactionManager {
	
	private static final long serialVersionUID = 1643700190511571847L;

	@Override
	protected Object doGetTransaction() throws TransactionException {
		return ConnectionUtils.getConnection();
	}

	@Override
	protected void doBegin(Object transaction, TransactionDefinition definition)
			throws TransactionException {
		Connection conn = (Connection) transaction;
		try {
			if(conn.getAutoCommit()) {
				conn.setAutoCommit(false);
			}
		} catch (SQLException e) {
			throw new RuntimeException("打开事务失败", e);
		}
	}

	@Override
	protected void doCommit(DefaultTransactionStatus status)
			throws TransactionException {
		Connection conn = (Connection) status.getTransaction();
		try {
			if(!conn.getAutoCommit()) {
				conn.commit();
			}
		} catch(SQLException e) {
			throw new RuntimeException("提交事务失败", e);
		}
	}

	@Override
	protected void doRollback(DefaultTransactionStatus status)
			throws TransactionException {
		Connection conn = (Connection) status.getTransaction();
		try {
			if(!conn.getAutoCommit()) {
				conn.rollback();
			}
		} catch(SQLException e) {
			throw new RuntimeException("回滚事务失败", e);
		}
	}
}